<?php
/**
 * 产品模块(后台)
 *
 * 产品service
 *
 * @author    zhouchao <zhouchao@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\ProductsService;

use App\Services\BaseService;
use App\Services\ImgServices\ImgTool;
use App\Services\ProductsService\ProductTrait\product_trait;
use App\Services\Tool\GeneralTool;
use App\Services\UserService\UserBackstage;
use App\Services\ProductTempService\ProductTempTool;
use App\Services\ColourService\ColourTool;
use App\Services\GiftService\GiftApiService;
use App\Services\UserService\UserTool;
use App\Services\PreferentialService\PreferentialService;
use App\Services\Exceptions\PriceErrorException;
use App\Services\SourcePicService\SourcePicTool;
use App\Services\Exceptions\ImageNotFoundException;
use App\Services\Exceptions\FontNotFoundException;
use DB;
use Log;

class ProductsBackService extends BaseService
{
    use product_trait;
    protected $user_backstage;
    protected $product_temp_tool;
    protected $userTool;

    public function __construct(UserBackstage $user_backstage,ProductTempTool $product_temp_tool,UserTool $userTool,SourcePicTool $source_pic_tool, ImgTool $img_tool)
    {
        $this->user_backstage = $user_backstage;
        $this->product_temp_tool = $product_temp_tool;
        $this->userTool = $userTool;
        $this->source_pic_tool = $source_pic_tool;
        $this->img_tool = $img_tool;
    }

    public function getList($type,$per_page=10)
    {
        $this->setParameter([
            'table' => 'products',
            'where' => [['channel','<>',7],['state','=',1]],
            'select'=>[
                'product_id', 'user_id', 'colour_id', 'product_temp_id','overflow_price',
                 'title', 'description', 'dig_num', 'collect_num','is_shelves','off_shelves_time',
                'is_infinite_time','remarks','sell_num','stock','is_infinite_stock','channel','is_show','updated_at','created_at'
            ],
            'order'=>'created_at',
            'sort' =>'desc'
        ]);
        switch($type){
            case 1 :
                $products = $this->getAllPaginated($per_page);
                break;
            case 2 :
                $this->where[] = array('is_shelves','=',1);
                $products = $this->getAllPaginated($per_page);
                break;
            case 3 :
                $user_ids = $this->user_backstage->get_user_id_list(1)->toArray();
                $this->whereIn = $user_ids;
                $products = $this->getAllByResourceIdsPaginated('user_id',10);
                break;
            case 4 :
                $user_ids = $this->user_backstage->get_user_id_list(2)->toArray();
                $this->whereIn = $user_ids;
                $products = $this->getAllByResourceIdsPaginated('user_id',10);
                break;
            default:
                $products = $this->getAllPaginated($per_page);
                break;
        }
        foreach($products as $product){
            //获取预览图
            $this->get_product_preview_images($product);
            $product->channel_name = array_search($product->channel,config('fashion.channel'));
        }
        return $products;
    }

    public function get_product_detail($product_id){
        try{
            $this->setParameter([
                'table' => 'products',
                'where' => [['state','=',1],['product_id','=',$product_id]],
                'select'=>[
                    'product_id', 'user_id', 'colour_id', 'product_temp_id','overflow_price',
                    'title', 'description', 'dig_num', 'collect_num','is_shelves','off_shelves_time',
                    'is_infinite_time','remarks','sell_num','stock','is_infinite_stock','channel','updated_at','created_at','price as original_price','preferential_price'
                ]
            ]);
            $product = $this->getById();
            if(!empty($product)){
                $product = $this->get_product_preview_images($product);
                //获取作品基本信息
                $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
                $product->brand_name = empty($product_temp) ? '' : $product_temp->brand_name;
                $product->product_temp_name = empty($product_temp) ? '' : $product_temp->product_temp_name;
                $colour_name = ColourTool::getColourSimpleInfoByColourId($product->colour_id);
                $product->colour = $colour_name;
                //尺码
                $size_names = ProductTempTool::getProdTempSizesByProdTempId($product->product_temp_id);
                //判断该件尺码是否有库存 能否出售
                $size_arr = array();
                if (empty($colour_name)) {
                    $r = 0;
                    foreach ($size_names as $size_name) {
                        $size_arr[$r]['size_name'] = $size_name;
                        $size_arr[$r]['num'] = 0;
                        $r = $r + 1;
                    }
                } else {
                    $r = 0;
                    foreach ($size_names as $size_name) {
                        $product_temp_stock = ProductTempTool::getStock($product->product_temp_id, $colour_name->colour_name, $size_name);
                        if (isset($product_temp_stock['stock']) && ($product_temp_stock['stock'] > 0)) {
                            //$size_arr[$size_name] = $product_temp_stock['stock'];
                            $size_arr[$r]['size_name'] = $size_name;
                            $size_arr[$r]['num'] = $product_temp_stock['stock'];
                            $r = $r + 1;
                        } else {
                            $size_arr[$r]['size_name'] = $size_name;
                            $size_arr[$r]['num'] = 0;
                            $r = $r + 1;
                        }
                    }
                }
                $product->sizes = $size_arr;
                $product->gift = GiftApiService::getProductGift(array('product_id' => $product->product_id));
                //获取用户头像名称
                $user = $this->userTool->userInfoByid($product->user_id);
                $product->nick_name = $user->nick_name;
                $product->avatar = $user->avatar;
                //$price_arr = $this->getTotalPrice($product);
//                $product->original_price = $price_arr['total_price'];
//                $product->preferential_price = $price_arr['total_preferential_price'];

                //模板
                $cost_detail_list = array();
                $cost_detail_list[] = array(
                    'resource_id'=>$product->product_temp_id,
                    'title'=>$product->brand_name.$product->product_temp_name,
                    'preferential_price'=>$product_temp->preferential_price,
                    'original_price'=>$product_temp->original_price,
                    'thumbnail'=>$product_temp->thumbnail,
                    'quantity'=>1,
                    'type'=>1
                );
                $source = array();
//                //获取素材价格
                $source_pic_ids = $this->getReSourceIds(
                    array(
                        array('product_id', '=', $product->product_id),
                        array('type', '=', 1), array('image_type', '=', 2),
                        array('state', '=', 1)
                    ),
                    'creative_id'
                );
                $source_pic_ids = array_unique($source_pic_ids);
                foreach ($source_pic_ids as $source_pic_id) {
                    //根据ID获取素材详情
                    $source_pic_result = $this->source_pic_tool->getSourcePicAvailableBySourcePicIdAndProdTempId($source_pic_id,$product->product_temp_id,2);
                    if($source_pic_result['state'] != 'M00000'){
                        throw new ImageNotFoundException('素材ID为'.$source_pic_id.',素材类型为2的原图片未找到,原因:'.$source_pic_result['message']);
                    }
                    $prices = PreferentialService::getResourcePrice($source_pic_id, 1);
                    if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
                        throw new PriceErrorException('ID为' . $source_pic_id . '的素材价格异常');
                    }
                    $source[] = array('resource_id'=>$source_pic_id,'title'=>$source_pic_result['result']->name,'preferential_price'=>$prices['preferential_price'],'original_price'=>$prices['original_price'],'thumbnail'=>env('IMG_URL_STD_PREFIX').$source_pic_result['result']->thumbnail,'quantity'=>1,'type'=>3);
                }
                //计算字体价格
                $font_ids = $this->getReSourceIds(
                    array(
                        array('product_id', '=', $product->product_id),
                        array('type', '=', 2),
                        array('state', '=', 1)
                    ),
                    'font_id'
                );
                $font_ids = array_unique($font_ids);
                foreach ($font_ids as $font_id) {
                    $font_path = DB::table('fonts')->where('font_id',$font_id)->value('font_path');
                    $font_name = DB::table('fonts')->where('font_id',$font_id)->value('font_name');
                    $font_image = DB::table('fonts')->where('font_id',$font_id)->value('font_image');
                    if(empty($font_path) || !is_file(public_path('fonts/').$font_path)){
                        throw new FontNotFoundException('地址为'.$font_path.'的字体未找到');
                    }
                    $prices = PreferentialService::getResourcePrice($font_id, 3);
                    if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
                        throw new PriceErrorException('ID为' . $font_id . '的字体价格异常');
                    }
                    $source[] = array('resource_id'=>$font_id,'title'=>$font_name,
                                      'preferential_price'=>$prices['preferential_price'],'original_price'=>$prices['original_price'],
                                      'thumbnail'=>env('IMG_URL_STD_PREFIX').$font_image,'quantity'=>1,'type'=>4);
                }
                //获取自定义素材
                $source_pic_ids = $this->getReSourceIds(
                    array(
                        array('product_id', '=', $product->product_id),
                        array('type', '=', 1), array('image_type', '=', 1),
                        array('state', '=', 1)
                    ),
                    'creative_id'
                );
                $source_pic_ids = array_unique($source_pic_ids);
                foreach ($source_pic_ids as $source_pic_id) {
                    //根据ID获取素材详情
                    $this->setParameter([
                        'table' => 'user_creatives',
                        'where' => [['creative_id','=',$source_pic_id],['state','=',1]],
                        'select'=> ['thumbnail','name','preferential_price','price as original_price']
                    ]);
                    $user_creatives = $this->getById();
                    if(empty($user_creatives)){
                        throw new ImageNotFoundException('素材ID为'.$source_pic_id.',素材类型为1的原图片未找到');
                    }
                    $source[] = array(
                        'resource_id'=>$source_pic_id,
                        'title'=>$user_creatives->name,
                        'preferential_price'=>$user_creatives->preferential_price,
                        'original_price'=>$user_creatives->original_price,
                        'thumbnail'=>env('IMG_URL_STD_PREFIX').$user_creatives->thumbnail,
                        'quantity'=>1,
                        'type'=>2
                    );
                }
                $cost_detail_list = array_merge($cost_detail_list,$source);
                $product->lists = $cost_detail_list;
            }
            return $product;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    public function product_exist($product_id){
        $this->setParameter([
            'table' => 'products',
            'where' => [['product_id','=',$product_id],['state','=',1]]
        ]);
        $count = $this->count();
        return $count;
    }

    public function get_products_by_ids($condition_name,$condition_ids){
        $product_ids = DB::table('products')->where([['state','=',1]])->whereIn($condition_name,$condition_ids)->pluck('product_id');
        return $product_ids;
    }

    public function get_shelves_product($is_shelves){
        $product_ids = DB::table('products')->where([['is_shelves','=',$is_shelves],['state','=',1]])->pluck('product_id');
        return $product_ids;
    }

    public function get_products_by_product_ids($product_ids){
        $products = DB::table('products')->whereIn('product_id',$product_ids)->where('state',1)->get()->toArray();
        foreach($products as $product){
            $this->get_product_preview_images($product);
        }
        return $products;
    }

    public function get_product_by_product_id($product_id){
        $product = DB::table('products')->where('product_id',$product_id)->where('state',1)->first();
        if(!empty($product)){
            $this->get_product_preview_images($product);
        }
        return $product;
    }

    /**
     * 获取产品图片
     * @param $product
     * @return mixed
     */
    public function get_product_preview_images($product)
    {
        //获取产品图片
        $previews = DB::table('product_preview_images')
            ->where(array(
                array('product_id', '=', $product->product_id),
                array('state', '=', 1)
            ))
            ->select('product_preview_original_image as original_image', 'product_preview_thumbnail_image as thumbnail')
            ->get();
        $product->original_image = array();
        $product->thumbnail = array();
        foreach ($previews as $preview) {
            $product->original_image[] = env('IMG_URL_STD_PREFIX') . $preview->original_image;
            $product->thumbnail[] = env('IMG_URL_STD_PREFIX') . $preview->thumbnail;
        }
        //是否有优惠 是否有赠品 获取赠品
        return $product;
    }

    /**
     * 更新产品
     * @param $input
     * @return mixed
     */
    public function update_product($input){
        return DB::table('products')->where('product_id',$input['product_id'])->update($input);
    }

    /**
     * 后台订单创建作品
     * @param $input
     * @return array
     */
    public function create_product($input){
        try{
            DB::beginTransaction();
            //user_id(1) channel colour_id craftsmanship_type craftsmanship_name position_type product_temp_id
            $create_date = array();
            if(isset($input['user_id']) && $input['user_id'] > 10000){
                $flag = $this->userTool->isUser( intval($input['user_id']));
                if($flag == false){
                    return $this->createResult('M00004',(object)array());
                }
                $create_date['user_id'] = intval($input['user_id']);
            }else{
                $create_date['user_id'] = 1;
            }
            if(!isset($input['product_temp_id']) || !is_numeric($input['product_temp_id'])){
                return $this->createResult('M00004',(object)array());
            }
            if(!isset($input['colour_name'])){
                return $this->createResult('M00004',(object)array());
            }
            $colour_id = ColourTool::getColourIdByColourName($input['colour_name']);
            //判断模板是否存在
            $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($input['product_temp_id'], $colour_id,1);
            if(empty($product_temp)){
                return $this->createResult('M12003',(object)array());
            }
            $create_date['product_temp_id'] = $input['product_temp_id'];
            $create_date['colour_id'] = $colour_id;
            //判断是否有图片
            if(!isset($input['preview_images'])){
                return $this->createResult('M00004',(object)array());
            }
            $input['preview_images'] = json_decode($input['preview_images']);
//            if(empty($input['preview_images'])){
//                return $this->createResult('M00004',(object)array());
//            }
            if($create_date['user_id'] == 1){
                $create_date['user_collection_id'] = 0;
            }else{
                $collection_id = DB::table('user_collections')->where([['user_id', '=', $create_date['user_id']], ['is_default', '=', 1]])->value('collection_id');
                $create_date['user_collection_id'] = empty($collection_id) ? 0 : $collection_id;
            }
            $create_date['is_shelves'] = 0;
            $create_date['price'] = $product_temp->original_price;
            $create_date['preferential_price'] = $product_temp->preferential_price;
            $create_date['channel'] = 7;
            $create_date['is_show'] = 0;
            $create_date['created_at'] = $create_date['updated_at'] = time();
            $create_date['product_id'] = GeneralTool::only_no();
            $create_date['prod_md5'] = md5(date('ymdhis') . rand(1, 10000) . $create_date['user_id']);
            $result = DB::table('products')->insert($create_date);
            if(empty($result)){
                return array('state'=>'M00001','result'=>(object)array(),'message'=>'创建失败');
            }
            //插入图片
            $create_preview_image_date = array();
            foreach($input['preview_images'] as $preview_image){
                //product_preview_original_image
//                if(!isset($preview_image->preview_image)){
//                    DB::rollback();
//                    return $this->createResult('M00004',(object)array());
//                }
                $create_preview_image_date['product_preview_original_image']
                    = $create_preview_image_date['product_preview_thumbnail_image']
                    = ImgTool::getImgPathByImgUrl($product_temp->thumbnail);
                if(isset($preview_image->preview_image)){
                    if(!ImgTool::imageUrlIsValid($preview_image->preview_image)){
                        return $this->createResult('M00004',(object)array());
                    }
                    $create_preview_image_date['product_print_image'] = $create_preview_image_date['product_print_thumbnail_image']
                        = ImgTool::getImgPathByImgUrl($preview_image->preview_image);
                }else{
                    $create_preview_image_date['product_print_image'] = $create_preview_image_date['product_print_thumbnail_image']
                        = '';
                }
//                $create_preview_image_date['product_print_image'] = $create_preview_image_date['product_print_thumbnail_image']
//                    = isset($preview_image->preview_image) ? ImgTool::getImgPathByImgUrl($preview_image->preview_image) : '';
                $create_preview_image_date['position_type'] = isset($preview_image->position_type) ? $preview_image->position_type : 1;
                $create_preview_image_date['craftsmanship_name'] = isset($preview_image->craftsmanship_name) ? $preview_image->craftsmanship_name : '打印';
                $create_preview_image_date['created_at'] = $create_preview_image_date['updated_at'] = time();
                $create_preview_image_date['product_id'] = $create_date['product_id'];
                $result = DB::table('product_preview_images')
                    ->insert($create_preview_image_date);
                if(empty($result)){
                    DB::rollback();
                    return array('state'=>'M00001', 'result'=>array(), 'message'=>'创建失败');
                }
            }
            return array('state'=>'M00000','result'=>array(
                'product_preview_image' => $product_temp->thumbnail,
                'product_id'=>$create_date['product_id'],
                'original_price' => $product_temp->original_price,
                'preferential_price' => $product_temp->preferential_price
            ),'message'=>'创建成功');
        }catch (\Exception $e){
            Log::info($e);
            DB::rollback();
            return array('state'=>'M00001','result'=>(object)array(),'message'=>'创建失败');
        }finally{
            DB::commit();
        }
    }

    /**
     * 保存后台自定义素材
     * @Author    zhouchao
     * @DateTime  2017-03-09
     * @copyright 2017 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     File $image
     * @param     int $plarform
     * @return    array
     */
    public function save_user_creatives($image, $platform)
    {
        $img_path = $this->img_tool->imgSave($image,2);
        if(empty($img_path)){
            return array('state'=>'M00001','result'=>(object)array(),'message'=>'保存失败');
        }
        $data['original_image'] = $img_path;
        $data['thumbnail'] = $this->img_tool->getImgThumbByImgPath($img_path,600,600,true);
        $data['user_id'] = env('MYTEE_OFFICIAL_USER_ID');
        $data['creative_id'] = date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $data['name'] = '官方素材';
        $data['price'] = $data['preferential_price'] = 0;
        $data['channel'] = $platform;
        $data['created_at'] = $data['updated_at'] = time();
        $result = DB::table('user_creatives')->insert($data);
        return empty($result) ? ['state'=>'M00001','result'=>(object)array(),'message'=>'保存失败'] : 
                                ['state'=>'M00000','result'=>array('creative_id'=>$data['creative_id'],'name'=>$data['name'],'thumbnail'=>env('IMG_URL_STD_PREFIX') . $data['thumbnail'],'price'=>$data['price'],'preferential_price'=>$data['preferential_price'],'type'=>2),'message'=>'保存成功'];
    }

    /**
     * 获取自定义素材
     * @Author    zhouchao
     * @DateTime  2017-03-09
     * @copyright 2017 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     int $user_id
     * @param     string $creative_id
     * @return    array
     */
    public function get_user_creatives($user_id, $creative_id)
    {
        $user_creative = DB::table('user_creatives')
          ->where(['user_id'=>$user_id,'creative_id'=>$creative_id,'state'=>1]) 
          ->first();
        return $user_creative;  
    }

    /**
     * 更新自定义素材的价格 包括实际价格和优惠价格
     * @Author    zhouchao
     * @DateTime  2017-03-09
     * @copyright 2017 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     array $input
     * @return    array
     */
    public function update_user_creatives_price($input)
    {
        $result = DB::table('user_creatives')
          ->where(['user_id'=>$input['user_id'],'creative_id'=>$input['creative_id'],'state'=>1]) 
          ->update($input);
        return empty($result) ? ['state'=>'M00001','result'=>(object)array(),'message'=>'修改失败'] : 
                                ['state'=>'M00000','result'=>$input,'message'=>'修改成功'];  
    }

    /**
     * 后台创建作品
     * @Author    zhouchao
     * @DateTime  2017-03-09
     * @copyright 2017 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     array $input
     * @return    array
     */
    public function create_product_from_backstage($input)
    {
        $result = [];
        try{
            DB::beginTransaction();
            //判断模板是否存在
            $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($input['product_temp_id'], $input['colour_id'],1);
            if(empty($product_temp)){
                $result = ['state'=>'M00001','message'=>'未找到模板','data'=>(object)array()];
                return $result;
            }
            if(!isset($input['positions']) || count($input['positions']) <= 0){
                $result = ['state'=>'M00001','message'=>'至少要选择一个位置','data'=>(object)array()];
                return $result;
            }

            // products product_preview_images product_prints product_print_materials
            $product_id = GeneralTool::only_no();
            $user_id = env('MYTEE_OFFICIAL_USER_ID');
            $collection_id = DB::table('user_collections')
                               ->where([['user_id', '=', $user_id], ['is_default', '=', 1]])
                               ->value('collection_id');
            $prod_md5 = md5(date('ymdhis') . rand(1, 10000) . $user_id);
            $insert_data = array();
            $insert_data['channel'] = 5;
            $insert_data['product_id'] = $product_id;
            $insert_data['prod_md5'] = $prod_md5;
            $insert_data['colour_id'] = $input['colour_id'];
            $insert_data['product_temp_id'] = $input['product_temp_id'];
            $insert_data['is_shelves'] = 1;
            $insert_data['user_collection_id'] = $collection_id;
            $insert_data['overflow_price'] = 0;
            $insert_data['off_shelves_time'] = 0;
            $insert_data['is_infinite_time'] = 1;
            $insert_data['stock'] = 0;
            $insert_data['is_infinite_stock'] = 1;
            $insert_data['user_id'] = $user_id;
            $insert_data['created_at'] = $insert_data['updated_at'] = time();
            $insert_product_result = DB::table('products')->insert($insert_data);
            if(empty($insert_product_result)){
                $result = ['state'=>'M00001','message'=>'创建失败','data'=>(object)array()];
                return $result;
            }

            // product_preview_images
            $has_preview = 0;
            foreach($input['positions'] as $position){
                if((isset($input['preview_'.$position]) && !empty($input['preview_'.$position])) 
                    && (isset($input['print_'.$position]) && !empty($input['print_'.$position])) 
                    && ((isset($input['source_'.$position.'_1']) && count($input['source_'.$position.'_1']) > 0) || (isset($input['source_'.$position.'_2']) && count($input['source_'.$position.'_2']) > 0))){
                    $has_preview = 1;
                    //保存预览图
                    $preview = $this->img_tool->imgSave($input['preview_'.$position],2);
                    $print = $this->img_tool->imgSave($input['print_'.$position],2);
                    $insert_preview_result = DB::table('product_preview_images')
                      ->insert(['product_id'=>$product_id,'product_preview_original_image'=>$preview,'product_preview_thumbnail_image'=>$preview,
                                'product_print_image'=>$print,'product_print_thumbnail_image'=>$print,'position_type'=>$position,'craftsmanship_name'=>isset($input['craftsmanship_name']) ? $input['craftsmanship_name'] : '打印',
                                'created_at'=>time(),'updated_at'=>time()]);
                    if(empty($insert_preview_result)){
                        $result = ['state'=>'M00001','message'=>'创建失败','data'=>(object)array()];
                        return $result;
                    }  

                    //保存
                    $insert_print_result = DB::table('product_prints')
                      ->insertGetId(['temp_id'=>$input['product_temp_id'],'user_id'=>$user_id,'product_id'=>$product_id,'colour_id'=>$input['colour_id'],'style_box_w'=>0,
                                'style_box_h'=>0,'sketchpad_width'=>0,'sketchpad_height'=>0,'position_type'=>$position,
                                'craftsmanship_name'=>isset($input['craftsmanship_name']) ? $input['craftsmanship_name'] : '打印','craftsmanship_type'=>isset($input['craftsmanship_type']) ? $input['craftsmanship_type'] : 1,'app_version'=>env('APP_VERSION'),
                                'created_at'=>time(),'updated_at'=>time()]);
                    if(empty($insert_print_result)){
                        $result = ['state'=>'M00001','message'=>'创建失败','data'=>(object)array()];
                        return $result;
                    }             

                    if(isset($input['source_'.$position.'_1'])){
                        foreach($input['source_'.$position.'_1'] as $source_pic_id){
                            //系统素材
                            $materials_result = DB::table('product_print_materials')  
                              ->insert(['product_id'=>$product_id,'product_print_id'=>$insert_print_result,'creative_id'=>$source_pic_id,'craftsmanship_type'=>isset($input['craftsmanship_type']) ? $input['craftsmanship_type'] : 1,
                                'craftsmanship_name'=>isset($input['craftsmanship_name']) ? $input['craftsmanship_name'] : '打印','type'=>1,'image_type'=>2,'edit_view_level'=>1,'font_svg'=>'','created_at'=>time(),'updated_at'=>time()]);
                            if(empty($materials_result)){
                                $result = ['state'=>'M00001','message'=>'创建失败','data'=>(object)array()];
                                return $result;
                            }   
                        }  
                    }

                    if(isset($input['source_'.$position.'_2'])){
                        foreach($input['source_'.$position.'_2'] as $source_pic_id){
                            //系统素材
                            $materials_result = DB::table('product_print_materials')  
                              ->insert(['product_id'=>$product_id,'product_print_id'=>$insert_print_result,'creative_id'=>$source_pic_id,'craftsmanship_type'=>isset($input['craftsmanship_type']) ? $input['craftsmanship_type'] : 1,
                                'craftsmanship_name'=>isset($input['craftsmanship_name']) ? $input['craftsmanship_name'] : '打印','type'=>1,'image_type'=>1,'edit_view_level'=>1,'font_svg'=>'','created_at'=>time(),'updated_at'=>time()]);
                            if(empty($materials_result)){
                                $result = ['state'=>'M00001','message'=>'创建失败','data'=>(object)array()];
                                return $result;
                            }   
                        }  
                    }
                }
            }
            if($has_preview == 0){
                $result = ['state'=>'M00001','message'=>'至少要一个位置有预览图、打印图和素材','data'=>(object)array()];
                return $result;
            }
            //素材 product_prints product_print_materials
            $product = DB::table('products')->where('product_id',$product_id)->select('product_id','product_temp_id','colour_id','overflow_price')->first();
            $prices = $this->getTotalPrice($product);
            //更新价格
            if($prices['total_price'] != 0 || $prices['total_preferential_price'] != 0){
                $product_price_flag = DB::table('products')->where('product_id',$product_id)->update(['price'=>$prices['total_price'],'preferential_price'=>$prices['total_preferential_price'],'updated_at'=>time()]);
                if(empty($product_price_flag)){
                    $result = ['state'=>'M00001','message'=>'创建失败','data'=>(object)array()];
                    return $result;
                }
            }
            $this->userTool->addCreateNumToAuthentication($user_id);
            //增加模板使用量
            ProductTempTool::increasedProdTempUsedNum($input['product_temp_id'],1);
            $result = ['state'=>'M00000','message'=>'创建成功','data'=>(object)array()];
            return $result;
        }catch (\Exception $e){
            Log::info($e);
            DB::rollback();
            $result = ['state'=>'M00001','message'=>'创建失败','data'=>(object)array()];
            return $result;
        }finally{
            if(empty($result) || $result['state'] != 'M00000'){
                DB::rollback();
            }
            DB::commit();
        }       
    }

}